import { defineEventHandler, readBody } from 'h3'
import redis from '../../util/redis'
import { checkAdminKey } from './_utils'
import { recordLog } from '../../util/log'

// POST /api/admin/ym.save with JSON { key, data }
export default defineEventHandler(async (event: any) => {
  const ck = await checkAdminKey(event)
  if (!ck.ok) return { status: event.node.res.statusCode || 401, message: ck.message }

  try {
    const body = await readBody(event) as any
    const key = body?.key
    const data = body?.data
    if (!key || typeof key !== 'string') {
      event.node.res.statusCode = 400
      return { status: 400, message: 'missing key' }
    }
    if (!data) {
      event.node.res.statusCode = 400
      return { status: 400, message: 'missing data' }
    }

    try {
      // allow optional days parameter to control expiry
      const days = Number(body?.days) || 0
      const ttl = days > 0 ? days * 24 * 3600 : 0
      const expiryAt = ttl > 0 ? new Date(Date.now() + ttl * 1000).toISOString() : null
      const payload = JSON.stringify({ ...data, updatedAt: new Date().toISOString(), expiryAt })
      if (ttl > 0) {
        await (redis as any).set(`ym:${key}`, payload, 'EX', ttl)
      } else {
        await (redis as any).set(`ym:${key}`, payload)
      }
      await recordLog(event as any, { message: `admin/ym: saved key=${key} ttl=${ttl}`, userId: 0 })
      return { status: 'ok', key, ttl }
    } catch (err: any) {
      event.node.res.statusCode = 500
      await recordLog(event as any, { message: `admin/ym: redis set failed ${String(err)}`, userId: 0 })
      return { status: 500, message: 'redis set failed', error: String(err) }
    }
  } catch (err: any) {
    event.node.res.statusCode = 500
    await recordLog(event as any, { message: `admin/ym: internal error ${String(err)}`, userId: 0 })
    return { status: 500, message: 'internal error', error: String(err) }
  }
})
